﻿var http = require('http'),
    querystring = require('querystring'),
    zlib = require('zlib');
var avNumber = 'av8670012';
var args = {
    //参数以及备用数据
    contents: querystring.stringify({
        //发包的信息
        name: 'www.bilibili.com',
    }),
};
var options = {
    hostname: 'www.bilibili.com',
    port: 80,
    path: '/video/' + avNumber + '/',
    method: 'GET',
    headers: {
        'Accept-Encoding': 'gzip, deflate',
    },
};
var get = function (options, args, callback) {
    var req = http.request(options, function (res) {
        var chunks = [], data, encoding = res.headers['content-encoding'];
        // 非gzip/deflate要转成utf-8格式
        if (encoding === 'undefined') {
            res.setEncoding('utf-8');
        }
        res.on('data', function (chunk) {
            chunks.push(chunk);
        });
        res.on('end', function () {
            var buffer = Buffer.concat(chunks);
            if (encoding == 'gzip') {
                zlib.gunzip(buffer, function (err, decoded) {
                    data = decoded.toString();
                    callback(err, args, res.headers, data);
                });
            } else if (encoding == 'deflate') {
                zlib.inflate(buffer, function (err, decoded) {
                    data = decoded.toString();
                    callback(err, args, res.headers, data);
                });
            } else {
                data = buffer.toString();
                callback(null, args, res.headers, data);
            }
        });
    });
    req.write(args.contents);
    req.end();
};
get(options, args, function (err, args, headers, data) {
    var regExp =/cid=(\d+)/g;
    var cid = regExp.exec(data);
    console.log(cid[1]);
    //console.log('==>header \n', headers);
    // console.log('==>data \n', data);
});